package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Comment;
import cn.wolfcode.trip.base.domain.LastTime;
import cn.wolfcode.trip.base.domain.Reply;
import cn.wolfcode.trip.base.mapper.CommentMapper;
import cn.wolfcode.trip.base.mapper.LastTimeMapper;
import cn.wolfcode.trip.base.mapper.ReplyMapper;
import cn.wolfcode.trip.base.query.CommentQueryObject;
import cn.wolfcode.trip.base.query.ReplyQueryObject;
import cn.wolfcode.trip.base.service.ICommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Bobo_Zhang
 */
@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ReplyMapper replyMapper;
    @Autowired
    private LastTimeMapper lastTimeMapper;
    @Override
    public PageInfo query(CommentQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Comment> list = commentMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void save(Comment comment) {
        comment.setCreatetime(new Date());
        commentMapper.insert(comment);

    }

    @Override
    public List<Reply> listReplyAll(ReplyQueryObject qo) {
        List<Reply> list = replyMapper.selectAll(qo);
        return list;
    }

    @Override
    public void saveReply(Reply reply) {
        reply.setCreatetime(new Date());
        replyMapper.insert(reply);
    }

    @Override
    public int selectCommentCount(Long id) {
        LastTime lastTime = lastTimeMapper.selectByPrimaryKey(id);
        if (lastTime.getLastMessageTime() == null) {//如果没有时间,就先添加访问时间
            LastTime time = new LastTime();
            time.setId(id);
            time.setLastMessageTime(new Date());
            lastTimeMapper.insert(time);
        }
        return commentMapper.selectCommentCount(id);
    }

    @Override
    public List<Map> selectOneCommentCount(Long id) {
        List<Map> maps = commentMapper.selectOneCommentCount(id);
        //改变上一次访问本页面的时间
        LastTime time = new LastTime();
        time.setId(id);
        time.setLastMessageTime(new Date());
        lastTimeMapper.updateByPrimaryKey(time);
        return maps;
    }
}
